"use strict"

var Router = require('koa-router');
var config = require('../../config/config.js');
var debug = require('debug')('router_user');
var dao = require('../../dao/user.js');
var md5 = require('../../common/app_utils.js').md5;

var ferror = require('../../common/app_utils.js').formatError;
var fout = require('../../common/app_utils.js').formatOutput;
var errInfo = require('../../common/err_info.js');

debug('router:' + config.http.baseUrl + '/v1/user');
var router = new Router({
	prefix: config.http.baseUrl + '/v1/user'
});
module.exports = router.routes();
/**
add a user, with role-permission
post /forum/v1/user 
{
	"email": "aa@bb.com",
	"phone": "13144025450",
	"name": "wzq",
	"password": "abc123",
	"rps": [{
		"orgnization": "root",
		"roles": "super_admin"
	}]
}
*/
router.post('/', function*() {
	// debug('add user');
	// check input TODO
	var inParams = this.request.inParams;
	var result = yield dao.create(inParams);
	this.body = result;
});

/**
check name/phone/email-passwd match or not
post /forum/v1/user/verify
{
	email: 'abc@xyz.com',
	password: 'abc123'
}
*/
router.post('/verify', function*() {
	// check input TODO
	var inParams = this.request.inParams;
	var result = yield dao.verify(inParams);
	// debug('verify', result);
	this.body = result;
});

// login: verify and set session
router.post('/login', function*() {
	var inParams = this.request.inParams;
	var result = yield dao.verify(inParams);
	if (result.errCode === 0) {
		debug('set session userId=', result.result._id);
		this.session.userId = result.result._id;
	}
	this.body = result;
});

router.get('/islogin', function*() {
	debug('islogin userId=', this.session.userId);
	if (this.session.userId) {
		this.body = fout('ok');
	} else {
		this.body = ferror(errInfo.E2007);
	}
});